<!--附属产品开发模块-->
<template>
  <div class="accessory_product_wrap">
    <el-button             
      @click="addConfig"
    >{{ $t("finance.addAccessoryProduct") }}</el-button>
    <el-dialog
      :title="$t('finance.addConfig')"
      :visible.sync="dialogFormVisible.addConfig"
      width="1200px"
      :before-close="closeAddConfig"
    >
      <el-form :model="formConfig" :rules="configFormRules" ref="formConfig">
        <el-row>
          <el-col :span="8">
            <el-form-item
              :label="$t('finance.productNumber') + ':'"
              :label-width="formLabelWidth"
              prop="id"
            >
              {{ formConfig.id }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              :label="$t('finance.productName')"
              :label-width="formLabelWidth"
              prop="name"
            >
              <el-input
                v-model="formConfig.name"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              :label="$t('finance.description')"
              :label-width="formLabelWidth"
              prop="remark"
            >
              <el-input
                v-model="formConfig.remark"
                auto-complete="off"
                type="textarea"
                maxlength="200"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item
              :label="$t('finance.status')"
              :label-width="formLabelWidth"
              prop="active"
            >
              <el-switch
                v-model="formConfig.active"
                :active-value="0"
                :inactive-value="1"
              ></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              :label="$t('finance.feeDeductionMethod')"
              :label-width="formLabelWidth"
              prop="deductType"
            >
              <el-select
                v-model="formConfig.deductType"
                :placeholder="$t('verify.plsChoose')"
                style="width: 100%"
              >
                <el-option
                  v-for="item in feeDeductionList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
                <!--激活-->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!--日利率-->
            <el-form-item
              :label="$t('finance.dailyInterestRate')"
              :label-width="formLabelWidth"
              prop="loanRateDay"
            >
              <el-input v-model="formConfig.loanRateDay"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <!--年利率-->
            <el-form-item
              :label="$t('finance.annualInterestRate') + ':'"
              :label-width="formLabelWidth"
            >
              {{
                (formConfig.loanRateYear = isNaN(formConfig.loanRateDay)
                  ? ""
                  : (formConfig.loanRateDay * 365).toFixed(5))
              }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!--利息-->
            <el-form-item
              :label="$t('finance.interest') + ':'"
              :label-width="formLabelWidth"
            >
              {{ (this.formConfig.interest = computeLoanRate) }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!--征信查询费-->
            <el-form-item
              :label="$t('finance.creditInquiryFee')"
              :label-width="formLabelWidth"
              prop="creditServiceFee"
            >
              <el-input v-model="formConfig.creditServiceFee"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <!--账号管理费-->
            <el-form-item
              :label="$t('finance.accountManagementFee')"
              :label-width="formLabelWidth"
              prop="accountServiceFee"
            >
              <el-input v-model="formConfig.accountServiceFee"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!--平台服务费-->
            <el-form-item
              :label="$t('finance.platformServiceFee')"
              :label-width="formLabelWidth"
              prop="platformServiceFee"
            >
              <el-input v-model="formConfig.platformServiceFee"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!--风险管理费-->
            <el-form-item
              :label="$t('finance.riskManagementFee')"
              :label-width="formLabelWidth"
              prop="riskServiceFee"
            >
              <el-input v-model="formConfig.riskServiceFee"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <!--砍头息费-->
            <el-form-item
              :label="$t('finance.beheadedInterest') + ':'"
              :label-width="formLabelWidth"
              prop="headInterest"
            >
              <span>
                {{ computeheadInterest }}
              </span>
            </el-form-item>
          </el-col>
          <el-col v-if="formConfig.deductType" :span="16">
            <el-form-item label-width="0px">
              <span class="tips-red"
                >（{{ $t("common.notice") }}：{{
                  $t("finance.beheadedInterest")
                }}
                =
                <span v-if="formConfig.deductType != '1'"
                  >{{ $t("finance.interest") }} </span
                ><span v-if="formConfig.deductType == 3">+ </span
                ><span v-if="formConfig.deductType != '2'"
                  >{{ $t("finance.creditInquiryFee") }} + </span
                ><span v-if="formConfig.deductType != '2'"
                  >{{ $t("finance.platformServiceFee") }} + </span
                ><span v-if="formConfig.deductType != '2'"
                  >{{ $t("finance.riskManagementFee") }} + </span
                ><span v-if="formConfig.deductType != '2'">{{
                  $t("finance.accountManagementFee")
                }}</span
                >）</span
              >
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <!--滞纳金-->
            <el-form-item
              :label="$t('finance.latePayment')"
              :label-width="formLabelWidth"
              prop="lateFee"
            >
              <el-input v-model="formConfig.lateFee"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!--罚息利率-->
            <el-form-item
              :label="$t('finance.penaltyInterestRate')"
              :label-width="formLabelWidth"
              prop="overdueRate"
            >
              <el-input v-model="formConfig.overdueRate"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!--罚息比例-->
            <el-form-item
              :label="$t('finance.ratioOfPenaltyInterest')"
              :label-width="formLabelWidth"
              prop="overdueProportion"
            >
              <el-input v-model="formConfig.overdueProportion"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <!--合同金额-->
            <el-form-item
              :label="$t('finance.contractAmount')"
              :label-width="formLabelWidth"
              prop="contractAmount"
            >
              <el-input v-model="formConfig.contractAmount"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!--放款金额-->
            <el-form-item
              :label="$t('finance.loanAmount') + ':'"
              :label-width="formLabelWidth"
              prop="loanAmount"
            >
              {{ (formConfig.loanAmount = computedLoanAmount) }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!--伪名-->
            <el-form-item
              :label="$t('finance.pseudonym') + ':'"
              :label-width="formLabelWidth"
              prop="kana"
            >
              <el-input :disabled='type =="edit"' v-model="formConfig.kana"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <!--借款期限-->
            <el-form-item
              :label="$t('finance.borrowingPeriod')"
              :label-width="formLabelWidth"
              prop="loanPeriod"
            >
              <el-input v-model="formConfig.loanPeriod">
                <span slot="append">{{ $t("common.day") }}</span>
              </el-input>
            </el-form-item>
          </el-col>
          <!--是否分期-->
          <el-col :span="8" v-if="showSpread">
            <el-form-item
              :label="$t('install.whetherInstall')"
              :label-width="formLabelWidth"
              prop="isInstallment"
            >
              <el-switch
                v-model="formConfig.isInstallment"
                :active-value="1"
                @change="isInstallmentChange"
                :inactive-value="0"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 分期组合列表 -->
        <div v-if="formConfig.isInstallment === 1">
          <el-row v-for="(ratioArr, index) in formConfig.ratioArr" :key="index">
            <el-col :span="8">
              <el-form-item
                :label="$t('install.repaymentDate', { x: index + 1 })"
                :label-width="formLabelWidth"
                :prop="'ratioArr.' + index + '.day'"
                :rules="configFormRules.repaymentDate"
              >
                <el-input v-model="ratioArr.day" :min="1">
                  <!-- <span slot="prepend">{{ $t("install.at") }}</span> -->
                  <span slot="append">{{ $t("common.day") }}</span>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                :label="$t('install.repaymentRatio', { x: index + 1 })"
                :label-width="formLabelWidth"
                :prop="'ratioArr.' + index + '.ratio'"
                :rules="configFormRules.repaymentRatio"
              >
                <el-input v-model="ratioArr.ratio" :min="1" :max="100">
                  <span slot="append">%</span>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" v-if="index > 0">
              <el-form-item>
                <i
                  class="el-icon-delete-solid icon-set"
                  :data-index="index"
                  @click="delateStage"
                ></i>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="formConfig.isInstallment === 1">
            <el-col>
              <el-form-item :label-width="formLabelWidth">
                <el-button @click="addNewStage" type="primary">{{
                  $t("common.add")
                }}</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <el-row>
          <el-col :span="8">
            <el-form-item :label-width="formLabelWidth">
              <el-button
                @click="showExtension"
                :disabled="dialogFormVisible.showExtensionSetting"
                type="primary"
                >{{ $t("common.deployExtension") }}</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>

        <!--配置展期部分-->
        <div v-if="dialogFormVisible.showExtensionSetting">
          <el-row>
            <el-col :span="12">
              <el-form-item
                :label-width="formLabelWidth"
                prop="isExtension"
                required
              >
                <el-radio-group
                  style="width: 100%"
                  v-model="formConfig.isExtension"
                >
                  <el-row class="conclusion_radio">
                    <el-col :span="12">
                      <el-radio :label="1">{{
                        $t("common.saveAndEnable")
                      }}</el-radio>
                    </el-col>
                    <el-col :span="12">
                      <el-radio :label="0">{{
                        $t("common.saveOnly")
                      }}</el-radio>
                    </el-col>
                  </el-row>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="10">
              <!--使用区间-->
              <el-form-item
                :label="$t('common.useInterval')"
                :label-width="formLabelWidth"
                :required="formConfig.isExtension === 1"
              >
                <el-col :span="11">
                  <el-form-item
                    prop="startDay"
                    style="margin-bottom: 0"
                    :required="formConfig.isExtension === 1"
                  >
                    <el-input v-model="formConfig.startDay"></el-input>
                  </el-form-item>
                </el-col>
                <el-col class="text_center" :span="2">-</el-col>
                <el-col :span="11">
                  <el-form-item
                    prop="endDay"
                    style="margin-bottom: 0"
                    :required="formConfig.isExtension === 1"
                  >
                    <el-input
                      v-model="formConfig.endDay"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item :label-width="formLabelWidth">
                <div>
                  <p>{{ $t("common.deployExtensionRules1") }}</p>
                  <p>{{ $t("common.deployExtensionRules2") }}</p>
                  <p>{{ $t("common.deployExtensionRules3") }}</p>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <!--最大允许展期次数-->
          <!-- <el-row> -->
          <!-- <el-col :span="8"> -->
          <!-- <el-form-item -->
          <!-- :label="$t('common.maxExtensionTimes')" -->
          <!-- :label-width="formLabelWidth" -->
          <!-- prop="maxExtensionTimes" -->
          <!-- :required="formConfig.isExtension === 1" -->
          <!-- > -->
          <!-- <el-input v-model="formConfig.maxExtensionTimes"></el-input> -->
          <!-- </el-form-item> -->
          <!-- </el-col> -->
          <!-- <el-col :span="8" :offset="2" style="line-height: 45px"> -->
          <!-- <span>{{ -->
          <!-- $t("verify.plsInputWithinPositiveInteger", { x: "100" }) -->
          <!-- }}</span> -->
          <!-- </el-col> -->
          <!-- </el-row> -->
          <!-- 展期最低金额设置 -->
          <el-row>
            <el-col :span="8">
              <el-form-item
                :label="$t('common.minimumAmountExtension')"
                :label-width="formLabelWidth"
                prop="extensionMinFee"
              >
                <el-input v-model="formConfig.extensionMinFee"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <!--展期日费率-->
              <el-form-item
                :label="$t('common.extensionRateByDay')"
                :label-width="formLabelWidth"
                prop="extensionRate"
                :required="formConfig.isExtension === 1"
              >
                <el-input
                  @keyup.enter.native="computedExtensionFeeByRate"
                  v-model="formConfig.extensionRate"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="2" style="line-height: 45px">
              <span>{{ $t("common.enterComputed") + "，" }}</span>
              <span>{{
                $t("common.enterComputedByRate", { x: extensionFee })
              }}</span>
            </el-col>
          </el-row>

          <el-row>
            <!--期限设置(日)-->
            <el-col :span="10">
              <el-row
                v-for="(extensionDayCfg, index) in formConfig.extensionDayCfg"
                :key="index"
              >
                <el-col :span="19">
                  <el-form-item
                    :label="
                      index === 0
                        ? $t('common.setPeriod') +
                          '(' +
                          $t('common.everyDay') +
                          ')'
                        : ''
                    "
                    :label-width="formLabelWidth"
                    :prop="'extensionDayCfg.' + index + '.day'"
                    :rules="configFormRules.extensionDayCfg"
                    :required="formConfig.isExtension === 1"
                  >
                    <el-input
                      @keyup.enter.native="
                        enterComputedExtensionFeeByPeriod(
                          index,
                          extensionDayCfg.day
                        )
                      "
                      v-model="extensionDayCfg.day"
                      maxlength="10"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="2">
                  <el-button
                    v-if="index !== 0"
                    @click="removedEadline(index, extensionDayCfg)"
                    type="danger"
                    icon="el-icon-minus"
                    circle
                    class="mgl-5"
                  ></el-button>
                </el-col>
              </el-row>
              <!-- <el-row> -->
              <!-- <el-col :span="20"> -->
              <!-- <el-form-item :label-width="formLabelWidth"> -->
              <!-- <el-button -->
              <!-- @click="adddEadline" -->
              <!-- type="primary" -->
              <!-- icon="el-icon-plus" -->
              <!-- ></el-button> -->
              <!-- </el-form-item> -->
              <!-- </el-col> -->
              <!-- </el-row> -->
            </el-col>
            <el-col :span="14">
              <el-row v-for="(item, index) in extensionFees" :key="index">
                <el-col :span="24" style="height: 70px; line-height: 45px">
                  <span>{{ $t("common.enterComputed") + "，" }}</span>
                  <span>{{
                    $t("common.enterComputedByPeriod", {
                      x: formConfig.extensionDayCfg[index].day
                        ? formConfig.extensionDayCfg[index].day
                        : " - ",
                      y: item,
                    })
                  }}</span>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item :label-width="formLabelWidth">
                <div>
                  <p>{{ $t("common.deployExtensionRules4") }}</p>
                  <p>{{ $t("common.deployExtensionRules5") }}</p>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAddConfig">{{ $t("common.cancel") }}</el-button>
        <el-button
          type="primary"
          :disabled="isClick"
          @click="submitAddConfig"
          >{{ $t("common.confirm") }}</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import floatObj from "@/libs/precisio";
import Pagination from "@/components/pagination";
import mixin from "@/service/mixin";
import { keyMap , domain} from "@/config";
let that = null;
export default {
  name: "systemConfig",
  components: {
    Pagination,
  },
  mixins: [mixin],
  data() {
    //还款天数
    let validatorDate = (rules,value,callback)=>{
      if (!(/(^[1-9]\d*$)/.test(value))) { 
        callback(new Error(this.$t('install.pleaseInputPositiveInteger')));
　　　　　　return false; 
　　　　}else { 
        callback()
　　　　} 
    };
    //分期还款比列
    let validatorRatio = (rules,value,callback)=>{
      function isNotANumber(val) { 
      　　var regPos = /^[0-9]+.?[0-9]*/
        if(regPos.test(val)){
          return true
        }else{
          return false
        }
      }
      if (!isNotANumber(value)||isNaN(value)) { 
        callback(new Error(this.$t('common.plsInputRightNub')));
        return false; 
      }
      if(!/^\d+(\.\d{1,2})?$/.test(value)){
        callback(new Error(this.$t('common.onlyInputOne')));
        return false; 
      }
      if(value<0||value>100){
        callback(new Error(this.$t('install.pleaseInputeRepayRatioRighr')));
        return false; 
      }else{
        callback()
      }
    }
    var headInterestContractAmount = (rule, value, callback) => {
      if (this.formConfig.headInterest && this.formConfig.contractAmount) {
        if (
          !/^([1-9]\d{0,6}(\.\d{1,2})?)|([0](\.\d{1,2})?)$/.test(
            this.formConfig.contractAmount
          )
        ) {
          callback(
            new Error(this.$tc("verify.pls7d2")) //"小数点前1~7位，小数点后1~2位的数字，如：200.00 , 0.12"
          );
        } else if (
          Number.parseFloat(this.formConfig.headInterest) >
            Number.parseFloat(this.formConfig.contractAmount) ||
          Number.parseFloat(this.formConfig.headInterest) ===
            Number.parseFloat(this.formConfig.contractAmount)
        ) {
          callback(
            new Error(this.$tc("verify.tipsContractAmountMHeadInterest"))
          ); //合同金额必须大于砍头息，请调整数据
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    // 展期配置下选项是否必填自定义校验规则
    var extensionFormisRequired = (rule, value, callback) => {
      if (value === "" && this.formConfig.isExtension === 1) {
        callback(new Error(this.$tc("verify.plsInput")));
      } else {
        callback();
      }
    };
    // 展期期限天数不能小于3天
    var setPeriodRule = (rule, value, callback) => {
      if (value && +value < 3) {
        callback(new Error(this.$tc("common.periodLeast3days")));
      } else {
        callback();
      }
    };
    // 展期使用区间开始
    var extensionStartDayRule = (rule, value, callback) => {
      if (value === "" && this.formConfig.endDay) {
        callback(new Error(this.$tc("verify.plsInput")));
      } else if (
        value &&
        this.formConfig.endDay &&
        parseFloat(value) > parseFloat(this.formConfig.endDay)
      ) {
        callback(new Error(this.$tc("verify.plsLessThanEndDays")));
      } else {
        callback();
      }
    };
    var extensionEndDayRule = (rule, value, callback) => {
      if (value === "" && this.formConfig.startDay) {
        callback(new Error(this.$tc("verify.plsInput")));
      } else if (
        value &&
        this.formConfig.startDay &&
        parseFloat(value) < parseFloat(this.formConfig.startDay)
      ) {
        callback(new Error(this.$tc("verify.plsGreaterThanStartDays")));
      } else {
        callback();
      }
    };
    return {
      showSpread:false,
      type: "",
      formLabelWidth: this.$i18n.locale === "zhCN" ? "180px" : "210px",
      isClick: false, //  防止重复提交开关
      formConfig: {
        isInstallment: 0, //是否分期
        id: "",
        name: "",
        kana:'',
        remark: "",
        deductType: "",
        active: "",
        accountServiceFee: "",
        loanPeriod: "",
        loanRateDay: "",
        loanRateYear: "",
        contractAmount: "",
        creditServiceFee: "",
        headInterest: "",
        initialHeadInterest: "",
        lateFee: "",
        loanAmount: "",
        interest: "",
        overdueRate: "",
        overdueProportion: "",
        platformServiceFee: "",
        product: "",
        riskServiceFee: "",
        isExtension: "",
        startDay: "",
        endDay: 0,
        extensionUseInterval: "",
        maxExtensionTimes: "",
        extensionRate: "",
        extensionMinFee:"",
        extensionDayCfg: [{ day: "" }],
        ratioArr: [],
        
      },
      configFormRules: {
        // id:[
        //     { required: true, message: this.$t('verify.plsInput'), trigger: 'blur' }
        // ],
        name: [
          {
            required: true,
            message: this.$t("verify.plsInput"),
            trigger: "blur",
          },
        ],
        kana:[
          {
            required: true,
            message: this.$t("verify.plsInput"),
            trigger: "blur",
          },
        ],
        // remark:[
        //     { required: true, message: this.$t('verify.plsInput'), trigger: 'blur' }
        // ],
        deductType: [
          {
            required: true,
            message: this.$t("verify.plsInput"),
            trigger: "blur",
          },
        ],
        active: [
          {
            required: true,
            message: this.$t("verify.plsInput"),
            trigger: "blur",
          },
        ],
        loanRateDay: [
          {
            required: true,
            message: this.$t("verify.plsInput"),
            trigger: "blur",
          }, //请输入日利率
          {
            //pattern: /^([1-9]\d{0,1}(\.\d{1,5})?)|([0](\.\d{1,5})?)$/,
            pattern: /^([1-9]\d{0,1})$|^(0|[1-9]\d{0,1})\.(\d{1,5})$/,
            message: this.$t("verify.pls2d5"), // 小数点前1~2位，小数点后1~5位的数字，如：10.00 , 0.12
            trigger: "blur",
          },
        ],
        creditServiceFee: [
          {
            required: true,
            message: this.$t("verify.plsInput"),
            trigger: "blur",
          }, //"请输入征信查询费"
          {
            //pattern: /^([1-9]\d{0,6}(\.[0]{1,2})?)|([0](\.[0]{1,2})?)$/,
            pattern: /^([1-9]\d{0,6})$|^(0|[1-9]\d{0,6})\.(\d{1,2})$/,
            message: this.$t("verify.pls7d2"), //'小数点前1~7位，小数点后1~2位的数字，如：200.00 , 0.12'
            trigger: "blur",
          },
        ],
        accountServiceFee: [
          {
            required: true,
            message: this.$t("verify.plsInput"),
            trigger: "blur",
          }, //"请输入账号管理费"
          {
            //pattern: /^([1-9]\d{0,6}(\.[0]{1,2})?)|([0](\.[0]{1,2})?)$/,
            pattern: /^([1-9]\d{0,6})$|^(0|[1-9]\d{0,6})\.(\d{1,2})$/,
            message: this.$t("verify.pls7d2"), //'小数点前1~7位，小数点后1~2位的数字，如：200.00 , 0.12'
            trigger: "blur",
          },
        ],
        //分期天数
        repaymentDate :[
          {
            required: true,
            message: this.$t("install.pleaseInputeRepayDate"),
            trigger: "blur",
          }, //"请输入借款期限"
          {
            validator:validatorDate,
            trigger: "blur",
          }
        ],
        //分期还款比列
        repaymentRatio : [
          {
            required: true,
            message: this.$t("install.pleaseInputeRepayRatio"),
            trigger: "blur",
          }, //"请输入借款期限"
          {
            validator:validatorRatio,
            trigger: "blur",
          }
        ],
        platformServiceFee: [
          {
            required: true,
            message: this.$t("verify.plsInput"),
            trigger: "blur",
          }, //"请输入平台服务费"
          {
            //pattern: /^([1-9]\d{0,6}(\.[0]{1,2})?)|([0](\.[0]{1,2})?)$/,
            pattern: /^([1-9]\d{0,6})$|^(0|[1-9]\d{0,6})\.(\d{1,2})$/,
            message: this.$t("verify.pls7d2"), //'小数点前1~7位，小数点后1~2位的数字，如：200.00 , 0.12'
            trigger: "blur",
          },
        ],
        riskServiceFee: [
          {
            required: true,
            message: this.$t("verify.plsInput"),
            trigger: "blur",
          }, //"请输入风险管理费"
          {
            //pattern: /^([1-9]\d{0,6}(\.[0]{1,2})?)|([0](\.[0]{1,2})?)$/,
            pattern: /^([1-9]\d{0,6})$|^(0|[1-9]\d{0,6})\.(\d{1,2})$/,
            message: this.$t("verify.pls7d2"), //'小数点前1~7位，小数点后1~2位的数字，如：200.00 , 0.12'
            trigger: "blur",
          },
        ],
        // headInterest: [
        //   { required: true, message: "请输入砍头息费", trigger: "blur" },
        //   {
        //     pattern: /^([1-9]\d{0,6}(\.[0]{1,2})?)|([0](\.[0]{1,2})?)$/,
        //     message: "小数点前1~7位，小数点后1~2位的数字，如：200.00 , 0.12",
        //     trigger: "blur"
        //   }
        // ],
        lateFee: [
          {
            required: true,
            message: this.$t("verify.plsInput"),
            trigger: "blur",
          }, // "请输入滞纳金"
          {
            //pattern: /^([1-9]\d{0,6}(\.[0]{1,2})?)|([0](\.[0]{1,2})?)$/,
            pattern: /^([1-9]\d{0,6})$|^(0|[1-9]\d{0,6})\.(\d{1,2})$/,
            message: this.$t("verify.pls7d2"), //'小数点前1~7位，小数点后1~2位的数字，如：200.00 , 0.12'
            trigger: "blur",
          },
        ],
        overdueRate: [
          {
            required: true,
            message: this.$t("verify.plsInput"),
            trigger: "blur",
          }, //"请输入罚息利率",
          {
            //pattern: /^([1-9]\d{0,1}(\.\d{1,3})?)|([0](\.\d{1,3})?)$/,
            pattern: /^([1-9]\d{0,1})$|^(0|[1-9]\d{0,1})\.(\d{1,5})$/,
            message: this.$t("verify.pls2d5"), // "小数点前1~2位，小数点后1~3位的数字，如：20.00 , 0.12"
            trigger: "blur",
          },
        ],
        overdueProportion: [
          {
            required: true,
            message: this.$t("verify.plsInput"),
            trigger: "blur",
          }, //"请输入罚息比例"
          // {pattern: /^([1-9]\d{0,6}(\.[0]{1,3})?)|([0](\.[0]{1,2})?)$/, message: '小数点前1~7位，小数点后1~2位的数字，如：200.00 , 0.12', trigger: 'blur'}
        ],
        contractAmount: [
          {
            required: true,
            message: this.$t("verify.plsInput"),
            trigger: "blur",
          }, //"请输入合同金额"
          {
            validator: headInterestContractAmount,
            trigger: "blur",
          },
        ],

        loanPeriod: [
          {
            required: true,
            message: this.$t("verify.plsInput"),
            trigger: "blur",
          }, //"请输入借款期限"
          {
            pattern: /^[1-9]\d*$/,
            message: this.$t("verify.plsInputInteger"),
            trigger: "blur",
          }, //"只能输入正整数"
        ],
        startDay: [
          {
            pattern: /^-?[0-9]\d*$/,
            message: this.$t("verify.inputInteger"),
            trigger: "blur",
          },
          { validator: extensionFormisRequired, trigger: ["blur", "change"] },
          { validator: extensionStartDayRule, trigger: ["blur", "change"] },
        ],
        endDay: [
          {
            pattern: /^-?[0-9]\d*$/,
            message: this.$t("verify.inputInteger"),
            trigger: "blur",
          },
          { validator: extensionFormisRequired, trigger: ["blur", "change"] },
          { validator: extensionEndDayRule, trigger: ["blur", "change"] },
        ],
        maxExtensionTimes: [
          {
            pattern: /^([1-9][0-9]{0,1}|100)$/,
            message: this.$t("verify.plsInputWithinPositiveInteger", {
              x: "100",
            }),
            trigger: "blur",
          },
          { validator: extensionFormisRequired, trigger: ["blur", "change"] },
        ],
        extensionMinFee:[
          {
            required:true,
            message: this.$t("verify.plsInput"),
            trigger: "blur",
          }
        ],
        extensionRate: [
          {
            pattern: /^([1-9]\d{0,1})$|^(0|[1-9]\d{0,1})\.(\d{1,3})$|^0$/,
            message: this.$t("verify.pls2d3"),
            trigger: "blur",
          },
          { validator: extensionFormisRequired, trigger: ["blur", "change"] },
        ],
        extensionDayCfg: [
          {
            pattern: /^\d+$/,
            message: this.$t("verify.plsInputInteger"),
            trigger: "blur",
          },
          { validator: extensionFormisRequired, trigger: ["blur", "change"] },
          { validator: setPeriodRule, trigger: ["blur", "change"] },
        ],
      },
      statusList: [
        { label: this.$t("finance.activation"), value: 1 }, // 激活
        { label: this.$t("finance.inactivated"), value: 2 }, // 未激活
      ],
      feeDeductionList: [
        { label: this.$t("finance.feeDeductionOption.1"), value: 1 }, // 先扣除服务费
        { label: this.$t("finance.feeDeductionOption.2"), value: 2 }, // 先扣除利息
        { label: this.$t("finance.feeDeductionOption.3"), value: 3 }, // 先扣除服务费和利息
      ],
      dialogFormVisible: {
        addConfig: false,
        editConfig: "",
        showExtensionSetting: false,
      },
      overdueType: keyMap.overdueType,
      keyMap,
      extensionFee: "", //展期日费率* 合同金额 回车计算结果
      extensionFees: [""], //展期日费率 * 合同金额 * 期限天数 回车计算结果
    };
  },
  methods: {
    isInstallmentChange(value){
      console.warn(value,this.type)
      if(value==0&&this.type!='edit'){
        this.formConfig.ratioArr=[]
      }
    },
    delateStage(e) {
      //删除分期数组
      let index = e.target.dataset.index;
      let ratioArr = this.formConfig.ratioArr;
      ratioArr.splice(index, 1);
      this.formConfig={
        ...this.formConfig,
        ratioArr
      }
    },
    addNewStage() {
      //新增分期
      let obj = {
        day: "",
        ratio: "",
      };
      let ratioArr = this.formConfig.ratioArr?this.formConfig.ratioArr:[];
      ratioArr.push(obj);
      this.formConfig={
        ...this.formConfig,
        ratioArr
      }     
    },
    fillParams(page = this.page) {
      const params = {
        page: {
          pageNo: page.currentPage,
          pageSize: this.page.pageSize,
        },
      };
      return params;
    },
    editConfig(row) {
      this.isClick = false;
      this.type = "edit";
      this.formConfig = Object.assign(this.formConfig, row);
      this.formConfig.extensionDayCfg = this.fillExtensionDayParam(
        this.formConfig.extensionDayCfg,
        "display"
      );
      if (this.formConfig.extensionUseInterval) {
        this.formConfig.startDay =
          this.formConfig.extensionUseInterval.split(",")[0];
        this.formConfig.endDay =
          this.formConfig.extensionUseInterval.split(",")[1];
      } else {
        this.formConfig.startDay = "";
        this.formConfig.endDay = "";
      }
      this.computedExtensionFeeByRate(); //回显根据展期费率计算结果
      this.extensionFees = this.computedExtensionFeesByPeriod; //回显根据展期费率 和 天数 计算结果
      this.dialogFormVisible.addConfig = true;
      if (this.formConfig.isExtension === 1) {
        this.dialogFormVisible.showExtensionSetting = true;
      }
      if(row.isInstallment===1){
        let dayArr = row.installmentDayCfg.split(',');
        let ratioArr = row.installmentRateCfg.split(',');
        let arr = []
        dayArr.forEach((item,index)=>{
           let obj = {
            day: "",
            ratio: "",
          };
          obj.day = item;
          obj.ratio = ratioArr[index]*100;
          arr.push(obj)
        });
        this.formConfig.ratioArr = arr;
      };
    },
    addConfig() {
      this.isClick = false;
      this.type = "add";
      this.formConfig = {
        isInstallment:0,
        id: "",
        name: "",
        kana:'',
        remark: "",
        deductType: "",
        active: "",
        accountServiceFee: "",
        loanPeriod: "",
        loanRateDay: "",
        loanRateYear: "",
        contractAmount: "",
        creditServiceFee: "",
        headInterest: "",
        initialHeadInterest: "",
        lateFee: "",
        loanAmount: "",
        interest: "",
        overdueRate: "",
        overdueProportion: "",
        platformServiceFee: "",
        product: "",
        riskServiceFee: "",
        isExtension: "",
        startDay: "",
        endDay: 0,
        extensionUseInterval: "",
        maxExtensionTimes: "",
        extensionMinFee:'',
        extensionRate: "",
        extensionDayCfg: [{ day: "" }],
        ratioArr:[],
      };
      this.extensionFee = "";
      this.extensionFees = [""];
      this.dialogFormVisible.addConfig = true;
    },
    closeAddConfig() {
      this.formConfig = {
        isInstallment:0,
        id: "",
        name: "",
        kana:'',
        remark: "",
        deductType: "",
        active: "",
        accountServiceFee: "",
        // basicFlag: "",
        loanPeriod: "",
        loanRateDay: "",
        loanRateYear: "",
        contractAmount: "",
        creditServiceFee: "",
        headInterest: "",
        initialHeadInterest: "",
        lateFee: "",
        loanAmount: "",
        interest: "",
        overdueRate: "",
        overdueProportion: "",
        platformServiceFee: "",
        product: "",
        riskServiceFee: "",
        isExtension: "",
        startDay: "",
        endDay: 0,
        extensionUseInterval: "",
        maxExtensionTimes: "",
        extensionRate: "",
        extensionMinFee:'',
        extensionDayCfg: [{ day: "" }],
        ratioArr:[]
      };
      this.extensionFee = "";
      this.extensionFees = [""];
      this.dialogFormVisible.showExtensionSetting = false;
      this.$refs.formConfig.clearValidate();
      this.dialogFormVisible.addConfig = false;
    },
    submitAddConfig() {
      this.$refs["formConfig"].validate((valid) => {
        if (valid) {
          if (!this.verifyExtensionDayRepeat()) {
            this.$message.error(this.$t("verify.plsSetDifferentDeadline"));
            return;
          }
          if (!this.verifyExtensionDaySort()) {
            this.$message.error(
              this.$t("verify.plsInputSmallToLargeExtensionPeriod")
            );
            return;
          }
          if(!this.spreadRatioCheck()&&this.formConfig.isInstallment){
            this.$message.error(this.$t("install.spreadRatioError"));
            return;   
          }
          if(!this.spreadDateCheck()&&this.formConfig.isInstallment){
            this.$message.error(this.$t("install.spreadDateError"));
            return;   
          }
          this.isClick = true;
          let params = Object.assign({}, this.formConfig);
          if (this.type === "add") {
            delete params.id;
          }
          delete params.startDay;
          delete params.endDay;
          params.extensionUseInterval = this.fillExtensionUseIntervalParam();
          params.extensionDayCfg = this.fillExtensionDayParam(
            this.formConfig.extensionDayCfg,
            "send"
          );
          params.extensionFeeCfg = this.computedExtensionFeesByPeriod.join();
          
          if(params.isInstallment){
            let spreadDay = [];
            let spreadRatio = [];
            this.formConfig.ratioArr.forEach(item=>{
              spreadDay.push(item.day);
              spreadRatio.push(item.ratio/100)
            })
            params.installmentDayCfg = spreadDay.join(',');
            params.installmentRateCfg = spreadRatio.join(',');
          }
          delete params.ratioArr;
          if(this.dialogFormVisible.showExtensionSetting){
            params.maxExtensionTimes = '100'
          }
          this.$api.finance.productSetting
            .updateAdditionalProductInfo(params)
            .then((res) => {
              const { status, data, error } = res;
              if ("1" === status && "00000000" === error && data) {
                if (data.flag === "true") {
                  this.$refs.formConfig.resetFields();
                  this.formConfig.ratioArr=[]
                  this.dialogFormVisible.addConfig = false;
                  this.dialogFormVisible.showExtensionSetting = false;
                  this.$message.success(data.msg);
                  this.$emit('getTableData')
                  // this.getTableData();
                  
                } else {
                  this.isClick = false;
                  this.$message.error(data.msg);
                }
              } else {
                this.isClick = false;
                this.$message.error(data.msg);
              }
            })
            .catch((res) => {
              this.isClick = false;
            });
        } else {
          return false;
        }
      });
    },
    // 展开 展期配置
    showExtension() {
      this.$refs["formConfig"].validate((valid) => {
        if (valid) {
          if (this.type === "add") {
            this.formConfig.isExtension = 1;
          }
          this.dialogFormVisible.showExtensionSetting = true;
        } else {
          this.$message.error(
            this.$t("verify.plsDeployMainProductInformation")
          );
        }
      });
    },
    // 删除期限天数
    removedEadline(index, extensionDayCfg) {
      if (this.formConfig.extensionDayCfg.length <= 1) {
        this.$message.error(this.$t("system.leastOneApp"));
        return;
      }
      this.formConfig.extensionDayCfg.splice(index, 1);
      this.extensionFees.splice(index, 1);
    },
    // 添加期限天数
    adddEadline() {
      if (this.formConfig.extensionDayCfg.length >= 3) {
        this.$message.error(this.$t("common.deployExtensionRules5"));
        return;
      }
      this.formConfig.extensionDayCfg.push({
        day: "",
      });
      this.extensionFees.push("");
    },
    // 计算每日展期费用
    computedExtensionFeeByRate() {
      let result = Math.round(
        Number.parseFloat(this.formConfig.contractAmount) *
          Number.parseFloat(this.formConfig.extensionRate)
      );
      this.extensionFee = isNaN(result) ? "" : result;
    },
    //回车计算不同期限内展期费用
    enterComputedExtensionFeeByPeriod(index) {
      this.extensionFees.splice(
        index,
        1,
        this.computedExtensionFeesByPeriod[index]
      );
    },
    //处理可展期天数参数格式
    fillExtensionDayParam(data, type) {
      if (type === "send") {
        let result = data.map((item) => {
          return item.day;
        });
        return result.join();
      } else if (type === "display") {
        let result = data.split(",").map((item) => {
          return { day: item };
        });
        return result;
      }
    },
    //处理可展期期限区间参数格式
    fillExtensionUseIntervalParam() {
      if (this.formConfig.startDay || this.formConfig.endDay) {
        return [this.formConfig.startDay, this.formConfig.endDay].join();
      } else {
        return "";
      }
    },
    //判断还款比列相加是否未100%
    spreadRatioCheck(){
      let {ratioArr} = this.formConfig;
      let totalRatio = 0
      ratioArr.forEach(item=>{
        totalRatio = totalRatio/1 + (item.ratio*100)/1
      });
      return totalRatio/100 == 100
    },
    //判断还款分期天数是否有相同
    spreadDateCheck(){
      let allNub = 0;
      this.formConfig.ratioArr.forEach((item) => {
        allNub = allNub/1 + item.day/1
      });
      return allNub == this.formConfig.loanPeriod;
    },
    // 判断期限天数数组内有无重复
    verifyExtensionDayRepeat() {
      let arr = [];
      this.formConfig.extensionDayCfg.forEach((item) => {
        if (item.day) {
          arr.push(item.day);
        }
      });
      let newArr = Array.from(new Set(arr));
      return arr.length === newArr.length;
    },
    // 判断期限天数是否从小到大排序
    verifyExtensionDaySort() {
      let data = this.formConfig.extensionDayCfg;
      if (data.length === 1) {
        return true;
      } else {
        for (let i = 0; i < data.length - 1; i++) {
          if (parseFloat(data[i].day) > parseFloat(data[i + 1].day)) {
            return false;
          }
        }
        return true;
      }
    },
  },
  created() {
    this.showSpread = domain.showSpread();
    that = this;
  },
  computed: {
    computeheadInterest: function () {
      // {{ this.form.headInterest=((Number.parseFloat(this.form.interest)+Number.parseFloat(this.form.creditServiceFee)+Number.parseFloat(this.form.platformServiceFee)+Number.parseFloat(this.form.riskServiceFee)+Number.parseFloat(this.form.accountServiceFee)
      let arr = [
        this.formConfig.interest,
        this.formConfig.creditServiceFee,
        this.formConfig.platformServiceFee,
        this.formConfig.riskServiceFee,
        this.formConfig.accountServiceFee,
      ];
      if (this.formConfig.deductType == 1) {
        arr = [
          this.formConfig.creditServiceFee,
          this.formConfig.platformServiceFee,
          this.formConfig.riskServiceFee,
          this.formConfig.accountServiceFee,
        ];
      }
      if (this.formConfig.deductType == 2) {
        arr = [this.formConfig.interest, ""];
      }
      if (this.formConfig.deductType == 3) {
        arr = [
          this.formConfig.interest,
          this.formConfig.creditServiceFee,
          this.formConfig.platformServiceFee,
          this.formConfig.riskServiceFee,
          this.formConfig.accountServiceFee,
        ];
      }
      let headInterest = arr
        .reduce((x, y) => {
          return floatObj.add(x, y, 4);
        })
        .toFixed(2);
      this.$set(this.formConfig, "headInterest", headInterest);
      // this.form.headInterest=headInterest
      return isNaN(headInterest) ? "" : headInterest;
    },
    computeLoanRate: function () {
      let loanRate = Math.round(
        Number.parseFloat(this.formConfig.contractAmount) *
          Number.parseFloat(this.formConfig.loanRateDay) *
          Number.parseFloat(this.formConfig.loanPeriod)
      );
      loanRate = isNaN(loanRate) ? "" : loanRate + ".00";
      return loanRate;
    },
    computedLoanAmount: function () {
      let loanAmount =
        this.formConfig.contractAmount - this.formConfig.headInterest;
      return isNaN(loanAmount) ? "" : loanAmount;
    },
    //实时计算不同天数对应的展期费
    computedExtensionFeesByPeriod() {
      console.warn('dsads')
      let extensionFees = this.formConfig.extensionDayCfg.map((item) => {
        let result =
          Math.round(
            Number.parseFloat(this.formConfig.contractAmount) *
              Number.parseFloat(this.formConfig.extensionRate)
          ) * Number.parseFloat(item.day);
        result = result.toString().split('');
        if(result[result.length-1]<=4){
          result[result.length-1] = 0;
          result = Number.parseFloat(result.join(''))
        }else{
          result[result.length-1] = 0;
          result = Number.parseFloat(result.join(''))+10
        };
        return isNaN(result) ? "" : result;
      });
      return extensionFees;
    },
    isCanAdd() {
      // 新增产品按钮
      return this.$store.getters.checkUserAuthority(
        "/finance/system-setting/add"
      );
    },
    isCanEdit() {
      // 编辑产品按钮
      return this.$store.getters.checkUserAuthority(
        "/finance/system-setting/edit"
      );
    },
  },
  filters: {
    deductType(type) {
      switch (type) {
        case 1:
          return that.$t("finance.feeDeductionOption.1");
        case 2:
          return that.$t("finance.feeDeductionOption.2");
        case 3:
          return that.$t("finance.feeDeductionOption.3");
        default:
          return type;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.icon-set {
  padding: 20px 20px 0;
}
.system-config {
  .content_panel_top {
    padding-bottom: 15px;
    padding-right: 30px;
  }
  .panel_title {
    margin-bottom: 0px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .panel_title_right{
      display: flex;
      align-items: right;
      .accessory_product_wrap{
        margin-right: 10px;
      }
    }
  }
  .tips-red {
    color: #f56c6c;
  }
  .el-form-item {
    margin-bottom: 30px;
  }
  .mgl-5 {
    margin-left: 5px;
  }
  .color_red {
    color: #e65057;
  }
}
</style>




































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































